<template>
  <GlobalDrawer
    v-model="visible"
    title="添加付款记录"
    size="40%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="付款金额" prop="amount">
        <el-input-number v-model="form.amount" :min="0" :precision="2" style="width: 100%" />
      </el-form-item>

      <el-form-item label="付款时间" prop="payment_time">
        <el-date-picker
          v-model="form.payment_time"
          type="datetime"
          placeholder="请选择付款时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="付款方式" prop="payment_method">
        <el-select v-model="form.payment_method" placeholder="请选择付款方式" style="width: 100%">
          <el-option
            v-for="item in paymentMethodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
      </el-form-item>

      <el-form-item label="凭证">
        <el-upload
          action="#"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">支持jpg/png/pdf格式，单个文件不超过10MB</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { orderApi, paymentApi } from '@/api/crm'
  import type { Payment, Option } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref()
  const submitting = ref(false)

  const form = reactive({
    amount: 0,
    payment_time: '',
    payment_method: 1,
    remark: '',
    voucher: '',
  })

  const rules = {
    amount: [{ required: true, message: '请输入付款金额', trigger: 'blur' }],
    payment_time: [{ required: true, message: '请选择付款时间', trigger: 'change' }],
    payment_method: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
  }

  const paymentMethodOptions = ref<Option[]>([])
  const fileList = ref([])

  // 获取选项数据
  const getOptions = async () => {
    try {
      const res = await orderApi.getPaymentMethodOptions()
      paymentMethodOptions.value = res.data
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 文件上传前处理
  const beforeUpload = (file: File) => {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      ElMessage.error('文件大小不能超过10MB')
      return false
    }
    return false // 阻止自动上传，需要手动处理
  }

  // 文件移除
  const handleRemove = (file: any, fileList: any[]) => {
    // 处理文件移除逻辑
  }

  // 文件超出限制
  const handleExceed = () => {
    ElMessage.warning('最多只能上传1个文件')
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      submitting.value = true

      const submitData: Omit<Payment, 'id'> = {
        order_id: props.orderId.toString(),
        amount: form.amount,
        payment_time: form.payment_time,
        payment_type: form.payment_method,
        remark: form.remark,
        status: 1,
        user_id: 1,
      }

      await paymentApi.create(submitData)
      ElMessage.success('付款记录添加成功')

      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.keys(form).forEach(key => {
      if (key !== 'payment_method') {
        ;(form as any)[key] = ''
      }
    })
    form.payment_method = 1
    form.amount = 0
    fileList.value = []

    visible.value = false
  }

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal) {
      getOptions()
    }
  })
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }
</style>
